package sipoc.gateway;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.core.MessagingTemplate;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import sipoc.messaging.channel.RouterChannel;
import sipoc.model.HbRequest;
import sipoc.model.HbResponse;

@Component
public class HbGatewayImpl implements HbGateway {

	private final MessagingTemplate messagingTemplate = new MessagingTemplate();

	@Autowired
	private RouterChannel routerChannel;

	@Override
	public HbResponse doHb(HbRequest request) {
		Message<Integer> message = getMessage(request);

		Message<?> response = sendAndReceive(message);

		return (HbResponse) response.getPayload();
	}

	private Message<?> sendAndReceive(Message<Integer> message) {
		return messagingTemplate.sendAndReceive(routerChannel, message);
	}

	private Message<Integer> getMessage(HbRequest request) {
		return MessageBuilder.withPayload(request.getSequence())
				.setHeader("assetId", request.getAssetId())
				.setHeader("countryCode", request.getCountryCode()).build();
	}

}
